<template>
  <div class="avatar-uploader">
    <!-- 头像展示和上传按钮 -->
    <div class="avatar-wrapper" @click="triggerUpload">
      <el-avatar :size="150" :src="croppedAvatar || defaultAvatar" />
      <div class="upload-mask">
        <el-icon :size="30"><EditPen /></el-icon>
        <span>点击修改头像</span>
      </div>
    </div>

    <!-- 文件选择 -->
    <input
        ref="fileInput"
        type="file"
        hidden
        accept="image/*"
        @change="handleFileChange"
    />

    <!-- 裁剪对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="裁剪头像"
        width="800px"
        destroy-on-close
    >
      <div class="cropper-container">
        <vue-cropper
            ref="cropper"
            :img="originalImage"
            :auto-crop="true"
            :fixed="true"
            :fixed-number="[1, 1]"
            :center-box="true"
            :high="true"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCrop">确认裁剪</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传进度 -->
    <el-dialog
        v-model="uploading"
        title="上传中"
        width="400px"
        :close-on-click-modal="false"
        :show-close="false"
    >
      <el-progress :percentage="uploadProgress" :stroke-width="15" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { VueCropper } from 'vue-cropper'
import {EditPen} from "@element-plus/icons-vue";
// import 'vue-cropper/dist/index.css'

const props = defineProps({
  defaultAvatar: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['upload-success'])

const fileInput = ref(null)
const cropper = ref(null)
const dialogVisible = ref(false)
const uploading = ref(false)
const uploadProgress = ref(0)
const originalImage = ref('')
const croppedAvatar = ref('')

const triggerUpload = () => {
  fileInput.value.click()
}

const handleFileChange = (e) => {
  const file = e.target.files[0]
  if (!file) return

  if (!/^image\/(jpeg|png|gif|webp)$/.test(file.type)) {
    ElMessage.error('图片格式不支持')
    return
  }

  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }

  const reader = new FileReader()
  reader.onload = (event) => {
    originalImage.value = event.target.result
    dialogVisible.value = true
  }
  reader.readAsDataURL(file)
}

const handleCrop = () => {
  cropper.value.getCropBlob((blob) => {
    const reader = new FileReader()
    reader.onload = () => {
      croppedAvatar.value = reader.result
      dialogVisible.value = false
      startUpload(blob)
    }
    reader.readAsDataURL(blob)
  })
}

const startUpload = async (blob) => {
  try {
    uploading.value = true
    // 模拟上传过程
    for (let i = 0; i <= 100; i++) {
      await new Promise(resolve => setTimeout(resolve, 30))
      uploadProgress.value = i
    }

    emit('upload-success', {
      url: URL.createObjectURL(blob),
      blob: blob
    })
    ElMessage.success('上传成功')
  } catch (error) {
    ElMessage.error('上传失败')
  } finally {
    uploading.value = false
  }
}
</script>

<style>
.avatar-uploader {
  display: inline-block;
  position: relative;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 50%;
}

.upload-mask span {
  font-size: 14px;
  margin-top: 8px;
}

.cropper-container {
  width: 100%;
  height: 500px;
  position: relative;
}

.vue-cropper {
  background: #f8f8f9;
  border-radius: 4px;
}

/* 覆盖默认样式 */
.vue-cropper .cropper-view-box,
.vue-cropper .cropper-face {
  border-radius: 50%;
}

@media (max-width: 768px) {
  .cropper-container {
    height: 300px;
  }
}
</style>